package com.leorui.schoollife.controller.impl

import com.leorui.schoollife.controller.IFriendCircleControl
import com.leorui.schoollife.entity.FriendCircleCommitResponse
import com.leorui.schoollife.entity.FriendCircleMessageResponse
import com.leorui.schoollife.entity.response.CommonResponse
import com.leorui.schoollife.mapper.IDBFriendCircle
import com.leorui.schoollife.mapper.IDBUser
import com.leorui.schoollife.utils.EncryptUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import java.lang.Exception

@Controller
class FriendCircleControllerImpl : IFriendCircleControl {
    @Autowired(required = false)
    var dbFriendCircleController: IDBFriendCircle? = null

    @Autowired(required = false)
    var dbUserController: IDBUser? = null

    @ResponseBody
    @PostMapping("/api/v1/pull_all_friend_circle_list")
    override fun getAllFriendCircleList(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "current_page", required = true) currentPage: Int,
            @RequestParam(name = "page_size", required = true) pageSize: Int,
    ): Map<Any?, Any?> {
        try {
            val friendList = dbFriendCircleController?.selectAllFriendCircleList(pageSize, (currentPage - 1) * pageSize)
                    ?: return FriendCircleMessageResponse(1, "服务器问题").toMap()
            friendList.forEach {
                it.isLove = dbFriendCircleController?.selectFriendCircleItemIsLove(account, it.conversationId!!) == 1
                it.loveCount = dbFriendCircleController?.countFriendCircleItemInLove(it.conversationId!!)
                it.commitList = dbFriendCircleController?.selectCommitByConversationId(it.conversationId!!)
                it.commitList?.forEach { item ->
                    item?.commitUser?.account?.let { account ->
                        item.commitUser = dbUserController?.getUserAccount(account)
                    }
                    item?.commitToWho?.account?.let { account ->
                        item.commitToWho = dbUserController?.getUserAccount(account)
                    }
                }
            }
            val countAll = dbFriendCircleController?.countFriendCircleInAll() ?: 0
            return FriendCircleMessageResponse(0, null, currentPage, currentPage * pageSize < countAll, friendList).toMap()
        } catch (e: Exception) {
            return FriendCircleMessageResponse(1, "database error ${e.message}").toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_personal_friend_circle_list")
    override fun getPersonalFriendCircleList(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "current_page", required = true) currentPage: Int,
            @RequestParam(name = "page_size", required = true) pageSize: Int,
    ): Map<Any?, Any?>? {
        try {
            val friendList = dbFriendCircleController?.selectAllFriendCircleListByAccount(account, pageSize, (currentPage - 1) * pageSize)
                    ?: return FriendCircleMessageResponse(1, "服务器问题").toMap()
            friendList.forEach {
                it.isLove = dbFriendCircleController?.selectFriendCircleItemIsLove(account, it.conversationId!!) == 1
                it.loveCount = dbFriendCircleController?.countFriendCircleItemInLove(it.conversationId!!)
                it.commitList = dbFriendCircleController?.selectCommitByConversationId(it.conversationId!!)
                it.commitList?.forEach { item ->
                    item?.commitUser?.account?.let { account ->
                        item.commitUser = dbUserController?.getUserAccount(account)
                    }
                    item?.commitToWho?.account?.let { account ->
                        item.commitToWho = dbUserController?.getUserAccount(account)
                    }
                }
            }
            val countAll = dbFriendCircleController?.countFriendCircleInAll() ?: 0
            return FriendCircleMessageResponse(0, null, currentPage, currentPage * pageSize < countAll, friendList).toMap()
        } catch (e: Exception) {
            return FriendCircleMessageResponse(1, "database error ${e.message}").toMap()
        }
    }

    @ResponseBody
    @RequestMapping("/api/v1/upload_friend_circle_photo")
    override fun uploadImage(account: String, file: MultipartFile?): String? {
        return null
    }


    // 发朋友圈
    @ResponseBody
    @PostMapping("/api/v1/add_friend_circle")
    override fun sendFriendCircleItem(
            @RequestParam(name = "whoPublish", required = true) whoPublish: String,
            @RequestParam(name = "msg", required = true) msg: String,
            @RequestParam(name = "location", required = false) location: String?,
            @RequestParam(name = "timestamps", required = true) timestamps: String,
    ): Map<Any?, Any?> {
        // 获取当前时间，并且转换成md5作为唯一的值
        val encryptUtils = EncryptUtils()
        val conversationId = encryptUtils.convert2MD5(System.currentTimeMillis().toString())
        try {
            if (location?.isNotEmpty() == true) {
                dbFriendCircleController?.addNewFriendCircleWithAll(conversationId, whoPublish, msg, location, timestamps)
            } else {
                dbFriendCircleController?.addNewFriendCircleWithTime(conversationId, whoPublish, msg, timestamps)
            }
        } catch (e: Exception) {
            return CommonResponse(1, e.message, false).toMap()
        }
        return CommonResponse(0, null, true).toMap()
    }

    @ResponseBody
    @PostMapping("/api/v1/delete_friend_circle")
    override fun deleteFriendCircleItem(whoPublish: String, conversationId: String): Map<Any?, Any?>? {
        return null
    }

    @ResponseBody
    @PostMapping("/api/v1/love_friend_circle_item")
    override fun loveFriendCircleItem(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "conversation_id", required = true) conversationId: String
    ): Map<Any?, Any?> {
        return try {
            dbFriendCircleController?.loveFriendCircleItem(account, conversationId)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, "${e.message}", false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/un_love_friend_circle_item")
    override fun unLoveFriendCircleItem(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "conversation_id", required = true) conversationId: String
    ): Map<Any?, Any?>? {
        return try {
            dbFriendCircleController?.unLoveFriendCircleItem(account, conversationId)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, "${e.message}", false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/commit_friend_circle_item")
    override fun commitFriendCircleItem(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "conversation_id", required = true) conversationId: String,
            @RequestParam(name = "msg", required = true) msg: String,
            @RequestParam(name = "timestamps", required = true) timestamps: String
    ): Map<Any?, Any?>? {
        return try {
            val encryptUtils = EncryptUtils()
            val commitId = encryptUtils.convert2MD5(System.currentTimeMillis().toString() + account)
            dbFriendCircleController?.addCommitBodyItem(commitId, account, msg, timestamps)
            dbFriendCircleController?.addCommitConversationItem(commitId, conversationId)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, "${e.message}", false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/commit_friend_circle_item_to_who")
    override fun commitFriendCircleItemToWho(
            @RequestParam(name = "account") account: String,
            @RequestParam(name = "conversation_id") conversationId: String,
            @RequestParam(name = "msg") msg: String,
            @RequestParam(name = "timestamps") timestamps: String,
            @RequestParam(name = "commit_to_who") toWho: String
    ): Map<Any?, Any?>? {
        return try {
            val encryptUtils = EncryptUtils()
            val commitId = encryptUtils.convert2MD5(System.currentTimeMillis().toString() + account)
            dbFriendCircleController?.addCommitBodyToWhoItem(commitId, account, msg, timestamps, toWho)
            dbFriendCircleController?.addCommitConversationItem(commitId, conversationId)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, "${e.message}", false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/delete_friend_circle_item_commit")
    override fun deleteCommitFriendCircleItem(
            @RequestParam(name = "conversation_id") conversationId: String,
            @RequestParam(name = "commit_id") commitId: String
    ): Map<Any?, Any?>? {
        dbFriendCircleController?.deleteConversationCommit(commitId, conversationId)
                ?: return CommonResponse(1, "数据库错误", false).toMap()
        dbFriendCircleController?.deleteCommit(commitId) ?: return CommonResponse(1, "数据库错误", false).toMap()

        return CommonResponse(0, null, true).toMap()
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_conversation_commit")
    override fun getConversationCommit(
            @RequestParam(name = "conversation_id") conversationId: String
    ): Map<Any?, Any?>? {
        return try {
            val commitList = dbFriendCircleController?.selectCommitByConversationId(conversationId)
                    ?: return FriendCircleCommitResponse(1, "service error").toMap()
            commitList.forEach {
                it?.commitUser?.account?.let { account ->
                    it.commitUser = dbUserController?.getUserAccount(account)
                }
                it?.commitToWho?.account?.let { account ->
                    it.commitToWho = dbUserController?.getUserAccount(account)
                }
            }
            FriendCircleCommitResponse(0, null, commitList).toMap()
        } catch (e: Exception) {
            FriendCircleCommitResponse(1, "service error: ${e.message}").toMap()
        }
    }
}